import React, {Component} from "react";
import {Modal, Toast} from "antd-mobile";
import LazyLoad from "react-lazyload";
import Login from "../Public/Components/Login";
import kefu from "../../images/kefu.png";
import kefuZz from "../../images/kefu_zz.png";
import Popup from "react-modal";
import {restApiRequest} from "../Public/Api/Public";
import BlockButton from "../Public/Components/BlockButton";
import PropTypes from "prop-types";

let data = [];
let router = null;

const customStyles = {
    overlay: {
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.4)'
    },
    content: {
        top: '50%',
        left: '50%',
        right: 'auto',
        bottom: 'auto',
        marginRight: '-50%',
        transform: 'translate(-50%, -50%)',
        padding: 0,
        backgroundColor: null,
        border: null
    }
};

export default class ProductDetail extends Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            data: JSON.parse(localStorage.getItem('ProductDetail')),//商品数据信息
            visible: false,
            modalIsOpen: false,
            guige: false,
        };
        data = this.state.data;
        router = this.context;
        this.openModal = this.openModal.bind(this);
        this.closeModal = this.closeModal.bind(this);
    }

    openModal() {
        this.setState({modalIsOpen: true});
    }

    closeModal() {
        this.setState({modalIsOpen: false});
    }


    componentWillMount() {
        window.scrollTo(0, 0)
        let instructionsHtml = data.major_product_detail_link;
        this.instructionsData(instructionsHtml);
    }


    componentDidMount() {

        let host = window.location.href;
        let product_url = "";
        if (host.indexOf('zzwx1') != -1) {
            product_url = "http://zzwx1.hidizhu.com/shop/product/jump?id=";
        } else {
            product_url = "http://weixin.hidizhu.com/shop/product/jump?id=";
        }
        product_url = product_url + this.state.data.major_product_id;
        window.setShareTimeline(this.state.data.share_title, product_url, this.state.data.share_image_url, this.state.data.share_description);
        window.setShareAppMessage(this.state.data.share_title, product_url, this.state.data.share_image_url, this.state.data.share_description);
    }

    instructionsData(url) {
        restApiRequest.fetchgetp(url).then((response) => {
            if (!response.ok) {
                var error = new Error(response.statusText);
                error.response = response;
                throw error;
            } else {
                return response.text();
            }
        }).then((response_json) => {

            this.setState({
                instructions: response_json
            });

        }).catch((ex) => {
            console.log(ex);
        });
    }

    //立即购买选择规格

    onBuy = key => (e) => {
        document.querySelector('.product-wrap').classList.add('popup-default');
        e.preventDefault(); // 修复 Android 上点击穿透
        this.setState({
            [key]: true,
        });
    }

    onClose = key => () => {
        document.querySelector('.product-wrap').classList.remove('popup-default');
        this.setState({
            [key]: false,
        });
    }

    render() {

        let big = '0';
        let small = '0';
        if (this.state.data.price != undefined) {
            let price_array = this.state.data.price.split('.');
            big = price_array[0];
            small = price_array[1].substr(0, 1);
        }

        return (
            <div className="product-wrap">
                {this.state.visible ? <Login/> : null}
                <div className="product-list">
                    <section className="product-list-imgbox">
                        <LazyLoad
                            offset={100}
                            debounce={500}
                            placeholder={
                                <section className="product-list-lazyload">
                                    <svg className="product-list-placeholder">
                                        <use xlinkHref={'#icon-ico_page_bottom_dog'}></use>
                                    </svg>
                                </section>
                            }
                        >
                            <img className="product-list-img" src={this.state.data.top_image_url}/>
                        </LazyLoad>

                        <section className="product-list-imgtips">
                            <svg>
                                <use xlinkHref='#icon-ico_corner_tag'></use>
                            </svg>
                            <section className="product-list-tips">
                                <p className="product-list-tipstext">{this.state.data.use_scope}</p>
                                <section className="product-list-price">
                                    <span>￥</span>
                                    <span>{big}</span>
                                    <span>.{small}</span>
                                </section>
                            </section>
                        </section>

                        <section className="product-arrows-box">
                            <div className="product-arrows-left"/>
                            <div className="product-arrows-right"/>
                        </section>

                    </section>

                    <section className="product-text-box">
                        <p>{this.state.data.major_product_shortname}</p>
                        <p>{this.state.data.major_product_name}</p>
                    </section>
                </div>

                <section className="product-top-placeholder">
                    <svg>
                        <use xlinkHref={'#icon-divide_product-card'}></use>
                    </svg>
                </section>

                <Title text={'使用说明'}/>
                <div style={{marginBottom: '.5rem'}}>
                    {JSON.parse(this.state.data.major_product_instruction_json).map((data, i) => (
                        <section key={i} className="product-instructions">
                            <span style={{width: '1.7rem'}}>{data.keyword + ':'}</span>
                            <span>{data.value}</span>
                        </section>
                    ))}
                </div>
                <Title text={'商品详情'}/>
                <section dangerouslySetInnerHTML={{__html: this.state.instructions}}
                         className="product-ditor">{}</section>

                <section className="product-bottom-placeholder">
                    <svg>
                        <use xlinkHref={'#icon-centerborder'}></use>
                    </svg>
                </section>

                <section className="product-nav">

                    <section className="product-nav-box">
                        <div className="product-nav-kefu" onClick={this.openModal}>
                            <svg>
                                <use xlinkHref={'#icon-ico_service_bottom_bar'}></use>
                            </svg>
                            <span>客服</span>
                        </div>
                        <button
                            className="product-nav-btn"
                            type="button"
                            onClick={this.onBuy('guige')}
                        >
                            立即购买
                        </button>
                    </section>

                </section>
                <Popup
                    ariaHideApp={false}
                    isOpen={this.state.modalIsOpen}
                    onRequestClose={this.closeModal}
                    style={customStyles}
                    contentLabel="kefu-alert"
                >
                    {
                        window.location.href.indexOf('zzwx1') != -1 ?
                            <img src={kefuZz} className="product-kefu-alert"/> :
                            <img src={kefu} className="product-kefu-alert"/>
                    }
                </Popup>

                <Modal
                    popup
                    visible={this.state.guige}
                    onClose={this.onClose('guige')}
                    maskClosable={true}
                    animationType="slide-up"
                >
                    <PopView/>
                </Modal>

            </div>
        );
    }

}

class Title extends Component {

    render() {

        return (
            <section className="home-title-wrap" onTouchStart={this.props.onPress}>
                <div className="home-title-line" style={{marginBottom: '.18rem'}}/>
                <div className="home-title-box">
                    <span>{this.props.text}</span>
                </div>
            </section>
        )
    }

}

class PopView extends Component {

    static contextTypes = {
        router: PropTypes.object
    }

    constructor(props, context) {
        super(props, context);
        this.state = {
            spec_product_name: null,//商品规格名称
            spec_product_date: '',//商品规格日期
            spec_time: null,//选中的商品规格日期
            spec_product_date_list: '',//商品日期列表
            spec_product_id: '',
            allow_refund: '',//是否允许退款
            index: null,//当前选择的规格id
            dateIndex: null,
            price: data.price,//当前规格销售价格
            visible: false,//是否显示登录窗口

        };
    }

    componentWillMount() {
    }

    //规格选择
    onSpec(i, item) {
        console.log(i.spec_product_id);
        this.setState({
            index: item,
            price: i.selling_price,
            allow_refund: i.allow_refund,
            spec_product_id: i.spec_product_id,
            spec_product_name: i.spec_product_name,
            spec_product_date_list: i.spec_product_date_list
        });
        // console.log(i.spec_product_date_list)
    }

    //格式化时间戳
    format(time) {
        let da = new Date(parseInt(time) * 1000);
        let year = da.getFullYear() + '年';
        let month = da.getMonth() + 1 + '月';
        let date = da.getDate() + '日';
        return (year + month + date);
    }

    //时间规格选择
    onDateSpec(i, item) {
        this.setState({
            dateIndex: item,
            spec_product_date: i.spec_product_date,
            spec_time: i.spec_time,
            spec_product_date_id: i.id
        })
    }

    //下单
    onOrder() {

        // console.log(this.state.spec_product_name,this.state.spec_time)
        let sessionKey = localStorage.getItem('sessionkey');
        console.log('sessionkey-->');
        console.log(sessionKey);
        // sessionKey = '53af2010b6c29b477dcdb255a83f8213';

        if (sessionKey === null) {
            //弹出登录界面
            this.setState({visible: true})
        } else {
            //已登录 弹出规格列表
            if (this.state.spec_product_name == null) {
                return Toast.info('请选择规格', 2);
            }
            if (this.state.spec_product_date_list.length > 0) {
                if (this.state.spec_time === null) {
                    return Toast.info('请选择时间', 2);
                }
            }
            this.context.router.history.push({
                pathname: '/OrderPay',
            });

            let pay_msg = {
                title: data.major_product_shortname,
                major_product_id: data.major_product_id,
                spec_product_id: this.state.spec_product_id,
                spec_product_date_id: '',
                spec_name: this.state.spec_product_name,
                selling_price: this.state.price,
                allow_refund: this.state.allow_refund,
                spec_time: this.state.spec_time != null ? this.format(this.state.spec_time) : null,
                spec_date_id: this.state.spec_product_date_id,
                order_form: data.order_form
            }

            localStorage.setItem('pay_msg', JSON.stringify(pay_msg))
        }
    }

    render() {

        let big = '0';
        let small = '0';
        if (this.state.price != undefined) {
            let price_array = this.state.price.split('.');
            big = price_array[0];
            small = price_array[1].substr(0, 1);
        }

        return (
            <section className="product-standard-wrap">

                {this.state.visible ? <Login onClosedCallback={
                    () => {
                        this.setState({visible: false});
                    }
                } onLoginCallback={(val) => {
                    this.setState({visible: false});
                }
                }/> : null}

                <section className="product-standard-top">
                    <img src={data.top_image_url} className="product-standard-img"/>
                    <div className="product-standard-titlewrap">
                        <div className="product-standard-text">{data.major_product_shortname}</div>
                        <div className="product-standard-price">
                            <span>￥</span>
                            <span>{big}</span>
                            <span>.{small}</span>
                        </div>
                    </div>
                </section>

                <div className="product-standard-line"/>

                <section className="product-standard-box">
                    <section className="product-standard-select">
                        <div className="product-standard-selecttitle">规格选择：</div>
                        {data.spec_product_id_list.map((i, item) => (
                            <button
                                key={item}
                                type="button"
                                className={this.state.index == item ? 'product-standard-btn-active' : 'product-standard-btn-default'}
                                onClick={() => this.onSpec(i, item)}>{i.spec_product_name}</button>
                        ))}

                    </section>

                    {
                        this.state.spec_product_date_list.length > 0 ?
                            <section>
                                <div className="product-standard-line"/>
                                <section className="product-standard-select">
                                    <div className="product-standard-selecttitle">时间选择：</div>
                                    {this.state.spec_product_date_list.map((i, item) => (
                                        <button key={item}
                                                className={this.state.dateIndex == item ? 'product-standard-btn-active' : 'product-standard-btn-default'}
                                                onClick={() => this.onDateSpec(i, item)}>{this.format(i.spec_time)}</button>
                                    ))}
                                </section>
                                <div style={{marginBottom: '.4rem'}}/>
                            </section>
                            : null
                    }
                </section>


                <BlockButton
                    btnName={'立即购买'}
                    onPress={() => this.onOrder()}
                    bgColor={'#FFE227'}
                    btnHeight={'1.28rem'}
                    btnWidth={'10rem'}
                    textColor={'#000'}
                    textSize={'.45rem'}
                    className={'product-standard-btn'}
                />
            </section>
        )
    }
}
